import React, {ComponentType, useCallback, useEffect, useState} from 'react';
import {Button, StyleSheet, Text, View} from 'react-native';
import {TouchableOpacity} from 'react-native-gesture-handler';
import {AuthAPI} from '../../api';
import {ToastManger} from '../../components/Toast';
import {BGView} from '../../components/View/BackGround';
import {store, useReduxState} from '../../store';
import {userActions} from '../../store/user';
import getPwdHash from '../../utils/getPwdHash';
import {ScreenID, STYLE_COLOR} from '../../variables';
import FormInput from './components/FormInput';
import LinearGradientBackground from './components/LinearGradientBackground';

interface State {
  phone?: string;
  pwd?: string;
}

const Login: ComponentType<any> = ({navigation}) => {
  const [state, setState] = useState<State>();

  const user = useReduxState('user');

  useEffect(() => {
    if (user.isLogged) {
      navigation.navigate(ScreenID.Welcome);
    }
  }, [navigation, user]);

  const login = useCallback(async () => {
    const pwdHex = getPwdHash(state?.phone!, state?.pwd!);
    try {
      const result = await AuthAPI.loginWithPwd(state?.phone!, pwdHex);
      console.log('result', result);

      if (result) {
        store.dispatch(userActions.onDidLogin());
        navigation.navigate(ScreenID.TabPage, {
          screen: ScreenID.MinePage,
        });
      }
    } catch (error) {
      ToastManger?.displayAlert({
        // @ts-ignore
        message: error.cnmsg || '网络连接超时，请点击重试 或切换网络重试。',
      });
    }
  }, [navigation, state?.phone, state?.pwd]);

  return (
    <BGView white>
      <LinearGradientBackground />

      <View
        style={{
          paddingTop: 96,
          paddingHorizontal: 44,
          flex: 1,
        }}>
        <Text style={styles.title}>登录</Text>
        <View style={styles.segmentedContainer}>
          <TouchableOpacity style={styles.subTitle}>
            <Text style={{color: STYLE_COLOR.TEXT_MAIN}}>账号密码登录</Text>
          </TouchableOpacity>
          <Text
            style={{
              paddingHorizontal: 16,
              color: STYLE_COLOR.TEXT_LIGHT_GREY,
            }}>
            |
          </Text>
          <TouchableOpacity style={styles.subTitle}>
            <Text>短信验证码登录</Text>
          </TouchableOpacity>
        </View>

        <View>
          <FormInput
            placeholder="请输入手机号"
            value={state?.phone}
            maxLength={11}
            onChangeText={payload => setState({...state, phone: payload})}
          />

          <FormInput
            placeholder="请输入密码"
            value={state?.pwd}
            secureTextEntry={true}
            returnKeyType="done"
            onChangeText={payload => setState({...state, pwd: payload})}
          />
        </View>
        <View style={{marginTop: 24}}>
          <Button
            title="登录"
            disabled={!(state?.phone && state?.pwd)}
            onPress={login}
          />
        </View>
      </View>
    </BGView>
  );
};

const styles = StyleSheet.create({
  title: {
    color: STYLE_COLOR.TEXT_MAIN,
    fontSize: 24,
    fontWeight: 'bold',
  },
  subTitle: {
    height: 40,
    justifyContent: 'center',
  },
  segmentedContainer: {
    flexDirection: 'row',
    marginTop: 40,
    alignItems: 'center',
  },
});

export default Login;
